﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;

//2010-04-09增加
using IBatisNet.DataMapper;
using IBatisNet.Utilities;
using Newtonsoft.Json;

namespace LDAP
{
    public class Common
    {
        //注：0ED094DB3187261B是加密后的“”，因为CryptoHelper.DES_Decrypt解密非加密数据会报错

        /// <summary>
        /// 
        /// </summary>
        public const string Empty = "0ED094DB3187261B";

        /*/// <summary>
        /// 版本发布日期
        /// </summary>
        public static string ReleaseDate = ConfigurationManager.AppSettings["ReleaseDate"] ?? "";*/

        /// <summary>
        /// 框架连接串
        /// </summary>
        public static readonly string SqlConnStr = ConfigurationSettings.AppSettings["SqlConnStr"] ?? Empty;

        /*/// <summary>
        /// DataStoreFolder数据存储目录 2010-08-06 ,用于配置一些具有写入权限的目录
        /// </summary>
        public static readonly string DataStoreFolder = (Settings.KeyValues["DataStoreFolder"] ?? "").ToString();*/
        
        /// <summary>
        /// 初始化的比对时间
        /// </summary>
        public static readonly DateTime TimeInit = DateTime.Parse("2009-1-1 0:0:0");

        #region 2010-04-09增加的，优化数据库操作代码

        /// <summary>
        /// 2010-04-09增加 批量插入数据到SQL SERVER 2005 里
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="destinationTableName"></param>
        /// <param name="columnMap">key是DataTable里的字段名，value是数据库表里的字段名称</param>
        /// <returns></returns>
        public static bool InsertBatch(DataTable dt, string destinationTableName, System.Collections.Hashtable columnMap)
        {
            //return true;

            if (dt == null || dt.Rows.Count == 0)
                return true;

            try
            {
                //数据批量导入sqlserver,创建实例,SqlBulkCopyOptions.UseInternalTransaction采用事务  复制失败自动回滚
                System.Data.SqlClient.SqlBulkCopy sqlbulk = new System.Data.SqlClient.SqlBulkCopy(SqlConnStr);
                //sqlbulk.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnRowsCopied); //订阅复制完成后的方法,参数是 sqlbulk.NotifyAfter的值
                //sqlbulk.NotifyAfter = dt.Rows.Count;

                //目标数据库表名
                sqlbulk.DestinationTableName = destinationTableName;

                //数据集字段索引与数据库字段索引映射
                foreach (string key in columnMap.Keys)
                {
                    if (dt.Columns.Contains(key))//如果含有该列，则
                        sqlbulk.ColumnMappings.Add(key, columnMap[key].ToString());
                }

                //导入
                sqlbulk.WriteToServer(dt);
                sqlbulk.Close();

                return true;
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);
                //NLog.Log.DefaultLog().Write(ex);
                return false;
            }
            finally
            {
                dt.Clear();
                dt.Dispose();
            }
        }

        /// <summary>
        /// 2010-04-09增加，把IBatisNet实体对象映射为一个DataTable
        /// </summary>
        private static Dictionary<string, DataTable> _cachedIBatisNetDataTable = new Dictionary<string, DataTable>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapKey"></param>
        /// <param name="mapper"></param>
        /// <returns></returns>
        public static DataTable GetEmptyDataTableForIBatisNetEntity(string mapKey, ISqlMapper mapper)
        {
            if (_cachedIBatisNetDataTable.ContainsKey(mapKey))
            {
                return _cachedIBatisNetDataTable[mapKey].Clone();
            }

            DataTable dt = new DataTable();

            //ResultMaps的key格式是 Task.TaskResult, BaseItem.BaseItemResult ....
            IBatisNet.DataMapper.Configuration.ResultMapping.ResultMap map = DefaultMapper.ResultMaps[mapKey] as IBatisNet.DataMapper.Configuration.ResultMapping.ResultMap;

            for (int i = 0; i < map.Properties.Count; i++)
            {
                dt.Columns.Add(map.Properties[i].PropertyName, map.Properties[i].MemberType);
            }

            //加入缓存
            lock (_cachedIBatisNetDataTable)
            {
                if (!_cachedIBatisNetDataTable.ContainsKey(mapKey))
                {
                    _cachedIBatisNetDataTable.Add(mapKey, dt);
                }
            }

            return dt.Clone();
        }

        /// <summary>
        /// 使用Common.DefaultMapper,而且resultMap的id="{0}.{0}Result"的格式
        /// </summary>
        /// <param name="entityName"></param>
        /// <returns></returns>
        public static DataTable GetEmptyDataTableForIBatisNetEntity(string entityName)
        {
            return GetEmptyDataTableForIBatisNetEntity(GetIBatisNetMapKey(entityName), DefaultMapper);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entityName"></param>
        /// <returns></returns>
        public static string GetIBatisNetMapKey(string entityName)
        {
            return string.Format("{0}.{0}Result", entityName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entityName"></param>
        /// <returns></returns>
        public static System.Collections.Hashtable GetColumnsMap(string entityName)
        {
            //key
            string mapKey = GetIBatisNetMapKey(entityName);

            //ht
            System.Collections.Hashtable ht = new System.Collections.Hashtable();

            //ResultMap
            IBatisNet.DataMapper.Configuration.ResultMapping.ResultMap map = DefaultMapper.ResultMaps[mapKey] as IBatisNet.DataMapper.Configuration.ResultMapping.ResultMap;

            for (int i = 0; i < map.Properties.Count; i++)
            {
                ht.Add(map.Properties[i].PropertyName, map.Properties[i].ColumnName);
            }

            return ht;
        }

        #endregion

        /// <summary>
        /// 2010-08-09 ，用来初始化一些组件的配置，或者是系统其他一些要初始化的东西
        /// </summary>
        public static void ApplicationInit()
        {

        }

        /// <summary>
        /// 默认的mapper
        /// </summary>
        public static ISqlMapper DefaultMapper
        {
            get
            {
                const string key = "my_mapper";
                return SqlMapperHelper.Instance.Get(key) ?? SqlMapperHelper.Instance.Add(key, SqlConnStr);
            }
        }

        public static ISqlMapper GetMapper(string key, object value)
        {
            return DefaultMapper;
        }

        //private static Settings _settings = null;//2010-08-17取消，使用单例模式


        /// <summary>
        /// 获取当前日期是一年中的第几周
        /// </summary>
        /// <returns></returns>
        public static string GetWeekOfYear()
        {
            System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
            int weekOfYear = gc.GetWeekOfYear(DateTime.Today, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);
            return DateTime.Today.Year + "," + weekOfYear;
        }

        /// <summary>
        /// 获取当前日期是一年中的第几月
        /// </summary>
        /// <returns></returns>
        public static string GetMonthOfYear()
        {
            return DateTime.Today.Year + "," + DateTime.Today.Month;
        }


        #region json 序列化
        /// <summary>
        /// 2010-09-24 增加 by 杜有发
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(object obj)
        {
            //2010-09-13 增加一下代码 by 杜有发
            JsonSerializerSettings settings = new JsonSerializerSettings
                                                  {
                                                      NullValueHandling = NullValueHandling.Ignore,
                                                      MissingMemberHandling = MissingMemberHandling.Ignore,
                                                      ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                                                      DefaultValueHandling = DefaultValueHandling.Ignore
                                                  };
            settings.Converters.Add(new Newtonsoft.Json.Converters.IsoDateTimeConverter());

            return JsonConvert.SerializeObject(obj, Formatting.None, settings);//2010-07-16 增加 by 杜有发，增加对rawjsonstring解析的支持
        }

        /// <summary>
        /// 2010-09-24 增加 by 杜有发
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T DeserializeObjectFromJson<T>(string value)
        {
            return JsonConvert.DeserializeObject<T>(value);
        }
        #endregion
    }
}
